package com.gwd.task.componts;

import com.gwd.task.entity.UserEntity;
import com.gwd.task.model.UserDTO;
import com.gwd.task.services.UserServer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * @author zhiyongming
 * @date 2020/12/16 18:04
 */
@Component
public class Cache {
    private ConcurrentMap<Long, String> userMap;

    @Resource
    private UserServer userServer;

    @Bean
    public void initUserCache() {
        userMap = userServer.findAll().stream().collect(Collectors.toConcurrentMap(UserDTO::getUserId, UserDTO::getUserName));
    }

    public void refresh(UserEntity entity) {
//        userMap.computeIfPresent(entity.getUserId(), (k, v) -> v = entity.getUserName());
//        userMap.computeIfAbsent(entity.getUserId(), k -> entity.getUserName());
        userMap.merge(entity.getUserId(), entity.getUserName(), (o, n) -> n);
        System.out.println(this.userMap);
    }

    /**
     * 匹配id
     * @param list 需要被匹配的数组
     * @param compare 比较的字段的get方法 getUserId
     * @param value 覆盖字段的set方法 setUserName
     */
    public void matchUserName(List<?> list, String compare, String value) {
        if (list.size() == 0) {
            return;
        }
        Class<?> className = list.get(0).getClass();
        try {
            Method MethodSet = className.getDeclaredMethod(value, String.class);
            Method MethodGet = className.getDeclaredMethod(compare);

            list.forEach(e -> {
                try {
                    Long userId = (Long) MethodGet.invoke(e);
                    String userName = userMap.get(userId);
                    MethodSet.invoke(e, userName);
                } catch (IllegalAccessException | InvocationTargetException illegalAccessException) {
                    illegalAccessException.printStackTrace();
                }
            });
        } catch (NoSuchMethodException ignored) {
            System.out.println("方法获取错误");
        }
    }

    /**
     * 匹配id 简化版
     * 不传compare与value时，默认为getUserId与setUserName
     * @param list 需要被匹配的数组
     */
    public void matchUserName(List<?> list) {
        matchUserName(list, "getUserId", "setUserName");
    }
}
